const { errorReflict } = require('../code-explain.js');
const fs = require('fs');

module.exports = {

  // 判断文件是否存在
  getStat(path) {
    return new Promise(resolve => {
      fs.stat(path, (err, stats) => {
        if (err) {
          resolve(false);
        } else {
          resolve(stats);
        }
      });
    })
  },

  // 全局替换
  replaceAll(str, reg, reg_new) {
    return str.replace(new RegExp(reg, 'gm'), reg_new);
  },

  // 将pageNo,pageSize转为limit,skip
  changePage(pageNo: Number = 1, pageSize: Number = 10): Object {
    return {
      offset: (<number>pageNo - 1) * <number>pageSize,
      limit: Number(pageSize)
    }
  },

  // 计算数据库所匹配的total数
  async dbTotal(dbName: string, match: Object = {}) {
    let group = await this.ctx.model[dbName].aggregate(match);
    console.log(`database ${dbName} have ${group.length} rows`);
    return group.length;
  },

  // 判断数据类型
  async whatType(custom_type) {
    let mod = Object.prototype.toString;
    let temp_type_str = mod.call(custom_type);
    temp_type_str = temp_type_str.slice(8, temp_type_str.length - 1);
    return temp_type_str;
  },

  // 设置错误信息标号
  getErrorMsg(code) {
    return {
      code: code,
      status: errorReflict[code]
    }
  },

  // 获取全局数据
  getGlobalConfig() {
    return {
      pageSize: 5
    };
  }
}
